<template>
  <div>
    <div style="display: flex;align-items: center;padding: 20px;">
      <label for="" style="width: 100px;">wsUrl:</label>
      <el-input v-model="webSocketUrl" style="width: 500px;"></el-input>
      <el-button type="primary" @click="checkInWeb">连接</el-button>
      <el-button @click="checkOutWeb">关闭</el-button>
      <span>{{infoStatus}}</span>
    </div>
    <div style="display: flex;align-items: center;padding: 20px;">
      <label for="" style="width: 100px;">信息</label>
      <el-input v-model="webSendMessage" style="width: 500px;"></el-input>
      <el-button type="primary" @click="sendMessageHandle">发送</el-button>
      <el-button type="primary" @click="playAudioHandle">解析语音</el-button>
    </div>
    <div style="display: flex;align-items: center;padding: 20px;">
      <label for="" style="width: 100px;">接收信息</label>
      <el-input type="textarea" v-model="webReceiveMessage"></el-input>
    </div>
  </div>
</template>

<script >
import RecordRTC from 'recordrtc'
import {encodeALaw,enCode} from "g711";
export default {
  name: 'webSocket',
  data(){
    return {
      webSocketUrl: 'wss://192.168.11.19:8200/hik/audio/audio?username=admin&password=ucan1588&channel=1',
      infoStatus: '',
      webSendMessage: '',
      webReceiveMessage: '',
      systemWS: null,
      dataBuffer: []
    }
  },
  methods:{
    playAudioHandle() {

      return
      console.log(this.dataBuffer, '===this.dataBuffer')
      // 假设你有一个ArrayBuffer类型的二进制数据
      this.dataBuffer.forEach(item=>{
        let arrayBuffer = new ArrayBuffer(item); // 这里填入你的ArrayBuffer数据

// 使用AudioContext来解码和播放音频数据
        let audioContext = new (window.AudioContext || window.webkitAudioContext)();

// 将ArrayBuffer解码为AudioBuffer
        audioContext.decodeAudioData(arrayBuffer, function(audioBuffer) {
          // 创建source节点并设置其buffer为解码后的audioBuffer
          let source = audioContext.createBufferSource();
          source.buffer = audioBuffer;
          source.connect(audioContext.destination); // 连接到输出设备
          source.start(); // 播放音频
        });
      })

    },
    checkInWeb(){
      let that = this;
      if(!this.systemWS){
        this.systemWS = new WebSocket(this.webSocketUrl);
      }
      // let systemWS = this.systemSocket
      this.systemWS.onopen = () => {
        console.log('systemWS 连接正常')
        this.infoStatus = 'systemWS 连接正常'
        this.startRecording()
      }
      this.systemWS.onmessage = (event) => {
        console.log('onmessage-todo', event)
        //接收对方发送的消息

        this.webReceiveMessage = event.data
      }
      this.systemWS.onclose = (event) => {
        console.log(event, 'close')
        this.infoStatus = '关闭'
        this.systemWS = null
        this.stopRecording()
      }
      this.systemWS.onerror = (event) => {
        console.log(event, 'error')
        this.infoStatus = '失败'
        this.systemWS = null
        this.stopRecording()
      }
    },
    checkOutWeb(){
      this.systemWS.close()
    },
    sendMessageHandle(){
      this.systemWS.send(this.webSendMessage)
    },
    floatTo16BitPCM(input) {
      const output = new Int16Array(input.length);
      for (let i = 0; i < input.length; i++) {
        const s = Math.max(-1, Math.min(1, input[i]));
        output[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
      }
      return output;
    },
    async startRecording(){
      const stream = await navigator.mediaDevices.getUserMedia({ audio: {
          sampleRate: 8000,  // G.711 要求 8kHz
          channelCount: 1    // 单声道
        }
      })
      this.streamRef = stream;
      this.mediaRecorder = new RecordRTC(stream, {
        type: 'audio',
        mimeType: 'audio/wav', // 强制 WAV 格式
        desiredSampRate: 8000,
        bufferSize: 4096,
        numberOfAudioChannels: 1,
        timeSlice: 50,
        // 禁用音频封装格式
        recorderType: RecordRTC.StereoAudioRecorder,
        disableLogs: true,
        audioBitsPerSecond: 64000, // 64kbps 对应 G.711 速率
        ondataavailable: (blob) => {
          blob.arrayBuffer().then(async buffer => {
            const pcmInt16 = this.floatTo16BitPCM(buffer);  // 转换为16位整型
            const g711Data = enCode(pcmInt16);
            await this.systemWS.send(g711Data);
          });
        }
      });

      this.mediaRecorder.startRecording()
      console.log(this.mediaRecorder, '----------------mediaRecorder', stream)

        // console.log('Recording complete', blob.data);
        // this.systemWS.send(e.data)
        // 处理录音数据
        // this.dataBuffer.push(e.data)
      this.isRecording = true;
    },

    stopRecording(){
      this.mediaRecorder.stopRecording()
      this.streamRef.getTracks().forEach(track => track.stop());
      this.isRecording = false
      this.voiceLoading = false
      // this.voiceLoading = true
      // closeTwoWayAudio({id: voiceView.selectedDevice}).then(res=>{
      //   if (res.code === 0){
      //     this.isRecording = false;
      //   }
      // }).finally(()=>{
      //   this.voiceLoading = false
      // })
    },
  }
}
</script>

<style scoped lang="scss">

</style>
